//前台不登录就可以访问的接口
var express = require('express');
const formidable = require('formidable'); //处理含有文件上传的表单
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const random = require('string-random');
const { Success, MError,Guest } = require("../utils/Result");// 封装统一接口返回方法
const Db = require("../utils/Db");
const { getUUID,getToken } = require("../utils");
const {checkToken,getuid} = require("../utils"); // 登录拦截中间件
const WXBizDataCrypt = require('../utils/Node/WXBizDataCrypt') //引入解密模块
var request = require('request'); //引入request模块
var app = express();

// 引入发送短信模块（使用阿里云的短信）
const Core = require('@alicloud/pop-core');
const cookiesession = require('cookie-session');
const { type } = require('os');

var router = express.Router();
const tableNameCate = 'category';//商品分类
const tableNameBanner = 'banner';//轮播图
const tableNameGoods = 'goods';//商品
const tableNameSpecs = 'specs';//规格表
const tableNameMember = 'member';//会员表
const tableNameSeck = 'seckill';//限时秒杀表
const tableNameCode = 'code';//微信登录测试使用
const tableNameOrder = 'shop_order'

//javascript  树形结构
function toTree(data) {
    // 删除 所有 children,以防止多次调用
    data.forEach(function(item) {
        delete item.children;
    });

    // 将数据存储为 以 id 为 KEY 的 map 索引数据列
    var map = {};
    data.forEach(function(item) {
        // 在该方法中可以给每个元素增加其他属性
        // item.text = item.name;
        if(item.pid == 0){
            map[item.id] = item;
        }  
    });
    var val = [];
    data.forEach(function(item) {
        // 以当前遍历项的pid,去map对象中找到索引的id
            var parent = map[item.pid];
            // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
            if (parent) {
                //  添加到父节点的子节点属性中
                (parent.children || (parent.children = [])).push(item);
            } else {
                //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
                val.push(item);
            }
    });

    return val;
}

// 商品搜索
router.get('/search',async(req,res)=>{
    const {keywords} = req['query'];
    if(!keywords){
        res.send(MError("缺少必要条件"));
        return;
    }
    let data = await Db.select(req, `SELECT id,goodsname,price,market_price,img FROM ${tableNameGoods} WHERE goodsname like '%${keywords}%' `);
    res.send(Success(data));
})


//获取分类信息
router.get("/getcate", async (req, res) => {
    let data = await Db.select(req, `SELECT * FROM ${tableNameCate} WHERE pid = 0 AND status = 1`);
    res.send(Success(data));
});

// 获取所有商品分类数据 返回分类树（递归）
router.get("/getcates", async (req, res) => {
    let data = await Db.select(req, `SELECT * FROM ${tableNameCate} WHERE status = 1`);
    // const data = await Db.select(req, `SELECT a.*,b.id,b.goodsname,b.img FROM ${tableNameCate} a LEFT JOIN ${tableNameGoods} b ON a.id = b.second_cateid WHERE a.status = 1`);
    // 将数据排序 父与子关系
    data = toTree(data)
    res.send(Success(data));
});

//获取轮播图信息
router.get("/getbanner", async (req, res) => {
    let data = await Db.select(req, `SELECT id,second_cateid,title,img FROM ${tableNameBanner} WHERE status = 1`);
    res.send(Success(data));
});

//获取限时秒杀
router.get("/getseckill",async(req,res)=>{
	
    // 当天0点
    var start = new Date(new Date(new Date().toLocaleDateString()).getTime()).getTime(); 
    // 当天23:59
    // var end = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1000).getTime();
    // let sql = `SELECT a.*,b.img,b.price FROM ${tableNameSeck} a LEFT JOIN ${tableNameGoods} b ON a.goodsid = b.id WHERE begintime >= ${start} AND endtime <= ${end}`;
    let data = await Db.select(req,`SELECT a.*,b.img,b.price FROM ${tableNameSeck} a LEFT JOIN ${tableNameGoods} b ON a.goodsid = b.id WHERE endtime > ${start}`);
    res.send(Success(data));
})

//获取首页商品-推荐、最新上架、所有商品
router.get("/gethortgoods",async(req,res)=>{
	let data1 = await Db.select(req, `SELECT id,goodsname,price,market_price,img FROM ${tableNameGoods} WHERE status = 1 AND ishot = 1 LIMIT 10`);
	let data2 = await Db.select(req, `SELECT id,goodsname,price,market_price,img FROM ${tableNameGoods} WHERE status = 1 AND isnew = 1 LIMIT 10`);
	let data3 = await Db.select(req, `SELECT id,goodsname,price,market_price,img FROM ${tableNameGoods} WHERE status = 1 LIMIT 10`);
	let data = [];
	data.push({content:data1});
	data.push({content:data2});
	data.push({content:data3});
	res.send(Success(data));
});

//获取分类下商品列表数据(支持分页)
router.get("/getgoodslist",async(req,res)=>{
    const {cateid,page,size} = req['query'];
    if(!cateid || !page || !size){
        return res.send(MError("缺少必要条件"));
    }
    let where = '';
    where = `WHERE status = 1  AND  second_cateid = ${cateid}`;
    let sql = `SELECT id,second_cateid,goodsname,price,market_price,img FROM ${tableNameGoods} ${where}`;
    if(size && page){
        let pagesize = (page-1)*size;//设置偏移量
    	sql += ` LIMIT ${pagesize},${size} `;
    }
    let goodsData = await Db.select(req,sql);
    // 获取总页数
    let countSql = `SELECT count(id) as count FROM ${tableNameGoods} ${where}`;
    let countNum = await Db.select(req,countSql);
    let total = Math.ceil(countNum[0].count / size);
    // 组装商品数据和总页码
    res.send(Success({total:countNum[0].count,goodsData}));
});

//获取一条商品信息
router.get("/getgoodsinfo", async (req, res) => {
    const {id} = req['query'];
    if (!id) {
        return res.send(MError("缺少必要条件"));
    }
    const info = await Db.select(req, `SELECT a.*,b.specsname FROM ${tableNameGoods} a LEFT JOIN ${tableNameSpecs} b ON a.specsid = b.id WHERE a.id = '${id}'`);
    res.send(Success(info, '获取成功'));
});




//注册
router.post("/register", async (req, res) => {
    let { phone,nickname,password } = req['body'];
    const info = await Db.select(req, `SELECT * FROM ${tableNameMember} WHERE phone = '${phone}'`);
    if (info) {
        res.send(MError("手机号已存在，不能重复！"));
    } else {
        const randstr = random(5);
        password += randstr;
        password = crypto.createHash('md5').update(password).digest("hex");
        const result = await Db.insert(req, tableNameMember, {
            uid: getUUID(),
            phone,
            nickname,
            password,
            avatarurl:"/uploads/tou.jpg",
            randstr,
            addtime:new Date().getTime(),
            status:1//新注册
        });
        if (result) {
            res.send(Success([], "注册成功"));
        } else {
            res.send(MError("注册失败"));
        }
    }
});

//登录
router.post("/login", async (req, res) => {
    let { phone,password } = req['body'];
    if(!phone || !password){
        res.send(MError("请填写手机号和密码"));
        return;
    }
    const result = await Db.select(req, `SELECT * FROM ${tableNameMember} WHERE  phone = '${phone}'`)
    if(result === null){
        res.send(MError("用户信息不存在"));
        return;
    }
    const info = result[0];
    password += info.randstr;
    password = crypto.createHash('md5').update(password).digest("hex");
    if(password !== info.password){
        res.send(MError("用户名密码错误"));
        return;
    }
    // 当用户登录时，直接获取登录时的token返给前端 ，有效时间为60秒
    let token = getToken(info['uid']);
    let data = {
    	token,uid:info.uid,phone:info.phone,nickname:info.nickname,avatarurl:info.avatarurl
    }
    res.send(Success(data, '登录成功'));
});




module.exports = router;